package van.planifolia.demo01;

import java.lang.reflect.Field;
import java.util.Arrays;

/**
 * Created by Intellij IDEA<br>
 * 通过反射来获取类中的字段信息
 * @author Planifolia.Van
 * @version 1.0
 * @date 2022/10/27 16:30
 */

public class ReflexGetFields {
    public static void main(String[] args) throws NoSuchFieldException {
        Class<People> peopleClass = People.class;
        Class<Doctor> doctorClass = Doctor.class;
        // getFields可以获取到所有的public字段，包括父类中的public字段
        Field[] fields = doctorClass.getFields();
        Arrays.stream(fields).forEach(System.out::println);
        System.out.println("======================================");

        // getField可以获取指定名字的public字段当然包括父类中的
        Field phoneNub = doctorClass.getField("phoneNub");
        System.out.println(phoneNub);
        System.out.println("======================================");

        // getDeclaredFields可以获取到当前类的所有字段包括private修饰的,但是不能获取父类的
        Field[] declaredFields = peopleClass.getDeclaredFields();
        Arrays.stream(declaredFields).forEach(System.out::println);
        System.out.println("======================================");

        // getDeclaredField可以获取指定的字段信息可以是本类的私有字段但是不能为父类
        Field name = peopleClass.getDeclaredField("name");
        System.out.println(name);

    }
}

class People{
    private String name;
    public String age;
}
class Doctor extends People{
    private String address;
    public String phoneNub;
}
